package cn.jiahua.hospital.controller;

import cn.jiahua.hospital.constants.ResultEnum;
import cn.jiahua.hospital.dto.OrderDto;
import cn.jiahua.hospital.dto.Page;
import cn.jiahua.hospital.dto.Result;
import cn.jiahua.hospital.dto.UserDto;
import cn.jiahua.hospital.pojo.Patients;
import cn.jiahua.hospital.pojo.User;
import cn.jiahua.hospital.pojo.YOrder;
import cn.jiahua.hospital.service.DepartmentsService;
import cn.jiahua.hospital.service.DoctorService;
import cn.jiahua.hospital.service.PatientsService;
import cn.jiahua.hospital.service.YOrderService;
import cn.jiahua.hospital.utils.RedisUtil;
import cn.jiahua.hospital.utils.ResultUtils;
import io.swagger.annotations.*;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Api
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Resource
    private YOrderService yOrderService;

    @Resource
    private PatientsService patientsService;

    @Resource
    private DoctorService doctorService;

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private DepartmentsService DepartmentsService;

    //后台查看订单信息，能够查看已经删除的信息,根据医院id查看
    @ApiParam(name = "id", value = "用户id")
    @ApiOperation(value = "根据医院id获取订单信息", notes = "后台系统，医院查看的订单信息")
    @GetMapping("getOrderByHospital")
    public Result getOrderByHospital(@RequestParam(value = "id", required = true) Integer id,
                                     @RequestParam(value = "pageNo", required = false) Integer pageNo,
                                     @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        //1、根据id获取用户订单的总数
        if (id == null) {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("hospitalId", id);
        Page<YOrder> yOrderPage = yOrderService.queryYOrderPageByMap(map, pageNo, pageSize);
        List<YOrder> yOrderListByMap = yOrderPage.getList();

        if (yOrderListByMap == null || yOrderListByMap.size() <= 0) {
            return ResultUtils.returnFail(ResultEnum.FAIL_DATA_NULL.getCode(), ResultEnum.FAIL_DATA_NULL.getMsg());
        }
        return ResultUtils.returnDataSuccess(yOrderPage);
    }


    //后台查看订单信息，能够查看已经删除的信息,根据医院id查看
    @ApiOperation(value = "根据用户id获取订单信息", notes = "个人中心查看订单信息")
    @GetMapping("getOrderByUser")
    public Result getOrderByUser(@RequestParam(value = "pageNo", required = false) Integer pageNo,
                                 @RequestParam(value = "pageSize", required = false) Integer pageSize,
                                 HttpServletRequest request) {
        List<UserDto> userDtoList = null;
        //1、根据id获取用户订单的总数
        String token = request.getHeader("token");
        if (token == null) {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        User user = (User) redisUtil.get(token);
        try {
            userDtoList = yOrderService.getOrderByUserId(user.getId());
            if (userDtoList == null || userDtoList.size()<=0) {
                return ResultUtils.returnFail(ResultEnum.FAIL_DATA_NULL.getCode(), ResultEnum.FAIL_DATA_NULL.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.returnFail("出现异常",ResultEnum.FAIL_DATA_NULL.getCode());
        }
        return ResultUtils.returnDataSuccess(userDtoList);
    }

    @ApiImplicitParam(name = "orderid", value = "订单编号")
    @PostMapping("cancelOrder")
    @ApiOperation(value = "用户取消订单", notes = "个人中心取消订单业务")
    public Result cancelOrder(@RequestBody Map<String,String> param) {
        String orderid = param.get("orderid");
        if (orderid == null || orderid == "") {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        //根据订单编号获取订单信息
        Map<String, Object> map = new HashMap<>();
        map.put("orderid", orderid);
        List<YOrder> yOrderListByMapOfUser = null;
        try {
            yOrderListByMapOfUser = yOrderService.getYOrderListByMapOfUser(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (yOrderListByMapOfUser == null || yOrderListByMapOfUser.size() <= 0) {
            return ResultUtils.returnFail(ResultEnum.FAIL_HAVE_NOT_EXIST.getCode(), ResultEnum.FAIL_HAVE_NOT_EXIST.getMsg());
        }

        //修改点订单的状态
        YOrder yOrder = yOrderListByMapOfUser.get(0);
        yOrder.setStatus(4);

        Integer integer = yOrderService.qdtxModifyYOrder(yOrder);

        if (integer <= 0) {
            return ResultUtils.returnFail(ResultEnum.FAIL_USER_UPDATE.getCode(), ResultEnum.FAIL_USER_UPDATE.getMsg());
        }
        return ResultUtils.returnSuccess();
    }

    @PostMapping("delOrder")
    @ApiImplicitParam(name = "orderid", value = "订单编号")
    @ApiOperation(value = "删除订单", notes = "个人中心删除丁页业务")
    public Result delOrder(@RequestParam String orderid) {
        if (orderid == null || orderid == "") {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        //根据订单编号获取订单信息
        Map<String, Object> map = new HashMap<>();
        map.put("orderid", orderid);
        List<YOrder> yOrderListByMapOfUser = null;
        try {
            yOrderListByMapOfUser = yOrderService.getYOrderListByMapOfUser(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (yOrderListByMapOfUser == null || yOrderListByMapOfUser.size() <= 0) {
            return ResultUtils.returnFail(ResultEnum.FAIL_HAVE_NOT_EXIST.getCode(), ResultEnum.FAIL_HAVE_NOT_EXIST.getMsg());
        }

        //修改点订单的状态
        YOrder yOrder = yOrderListByMapOfUser.get(0);
        yOrder.setDeleted(1);

        Integer integer = yOrderService.qdtxModifyYOrder(yOrder);

        if (integer <= 0) {
            return ResultUtils.returnFail(ResultEnum.FAIL_USER_UPDATE.getCode(), ResultEnum.FAIL_USER_UPDATE.getMsg());
        }
        return ResultUtils.returnSuccess();
    }

   /* @PostMapping("addOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id",required = true),
            @ApiImplicitParam(name = "price", value = "总价",required = true),
            @ApiImplicitParam(name = "doctorId", value = "医生id",required = true),
            @ApiImplicitParam(name = "hospitalId", value = "医院id",required = true),
            @ApiImplicitParam(name = "numType", value = "类型",required = true),
    })
    @ApiOperation(value = "添加订单")
    public Result addOrder(Integer userId,Double price,Integer doctorId,Integer hospitalId,Integer numType) {
        YOrder yOrder = new YOrder();
        yOrder.setUserId(userId);
        yOrder.setPrice(price);
        yOrder.setDoctorId(doctorId);
        yOrder.setHospitalId(hospitalId);
        yOrder.setNumType(numType);
        if(yOrder!=null){
            System.out.println("gg");
            int i = yOrderService.qdtxAddYOrder(yOrder);
            if(i>0){
                return ResultUtils.returnSuccess();
            }
        }

        return ResultUtils.returnFail();
    }*/

    @PostMapping("addOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id",required = true),
            @ApiImplicitParam(name = "price", value = "总价",required = true),
            @ApiImplicitParam(name = "doctorId", value = "医生id",required = true),
            @ApiImplicitParam(name = "hospitalId", value = "医院id",required = true),
            @ApiImplicitParam(name = "numType", value = "类型",required = true),
    })
    @ApiOperation(value = "添加订单")
    public Result addOrder(@Validated YOrder yOrder, HttpServletRequest request, HttpServletResponse response) {
        Integer random = RandomUtils.nextInt(10000000,99999999);
        String token = request.getHeader("token");
        if (token == null || token == "") {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        User user = (User) redisUtil.get(token);
        if (user == null ) {
            try {
                response.sendRedirect("/hospital/page/login.html");
                return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Map patientMap = new HashMap();
        Map doctorMap = new HashMap();
        Map departmentMap = new HashMap();
        String  time = String.valueOf(System.currentTimeMillis());
        if(yOrder!=null){
            yOrder.setDeleted(0);
            yOrder.setOrderid(time+random);
            yOrder.setStatus(1);
            yOrder.setUserId(user.getId());
            patientMap.put("userId",yOrder.getUserId());
            ArrayList<Patients> patientsList = (ArrayList<Patients>) patientsService.getPatientsListByMap(patientMap);
            if(patientsList.size()>0){
                yOrder.setPatientId(patientsList.get(0).getPatientsId());
                yOrder.setPatientsTime(patientsList.get(0).getSeeDoctorTime());
            }
            int i = yOrderService.qdtxAddYOrder(yOrder);
            if(i>0){
                return ResultUtils.returnDataSuccess(yOrder.getOrderid());
            }
        }

        return ResultUtils.returnFail();
    }



    @GetMapping("appointment")
    @ApiImplicitParam(name = "orderid", value = "订单id")
    @ApiOperation(value = "查看订单", notes = "根据订单id查看订单")
    public Result getOrder(String orderid){
        if (orderid == null || orderid == "") {
            return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
        }
        YOrder yOrder = yOrderService.getYOrderById_orderid(orderid);
        if(yOrder==null){
            return ResultUtils.returnFail(ResultEnum.FAIL_HAVE_NOT_EXIST.getCode(), ResultEnum.FAIL_HAVE_NOT_EXIST.getMsg());
        }
        return  ResultUtils.returnDataSuccess(yOrder);
    }

    @GetMapping("getOrderByOrderId")
    @ApiImplicitParam(name = "orderId",value = "订单单号")
    @ApiOperation(value = "根据订单id查看订单",notes = "根据订单id查看订单详情信息")
    public Result getOrderByOrderId(@RequestParam(value = "orderId",required = true)String orderId){
        try {
            if (orderId == null || orderId == "") {
                return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
            }
            OrderDto orderDto = yOrderService.getOrderInfoByOrderId(orderId);
            if (orderDto == null){
                return ResultUtils.returnFail(ResultEnum.FAIL_HAVE_NOT_EXIST.getCode(), ResultEnum.FAIL_HAVE_NOT_EXIST.getMsg());
            }
            return  ResultUtils.returnDataSuccess(orderDto);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.returnFail(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
        }
    }
}
